#define MXMODULE_VECTOR

#include "detk/region.h"
#include "deds/deds.h"
#include <assert.h>

/** This function clips the rectangles in a region by another rectangle.  
After the function returns the none of the rectangles in the region intersect
with the rectangle indicated. */
void mx_region_clip(MX_REGION * region, const MX_RECT * therect)
{
	unsigned int i;
	unsigned int num = mx_vector_size(region);

	MX_RECT rrect;

	rrect = *therect;
	assert(region);
	assert(therect);

	if (!MXRECT_VALID(rrect))
		return;

	/* Make a list of intersecting rectangles */
	for (i = 0; i < num; i++) {
		MX_RECT s = region->data[i];
		MX_RECT trial;

		MXRECT_INTERSECT(s, rrect, trial);
		if (MXRECT_VALID(trial)) {

			/* Remove the intersecting rectangles */
			mx_vector_remove(region, i, 1);
			--i, --num;

			/* Add to a temp list of the clipped rectangles */
			MX__TOP_RECTS(s, rrect, trial);
			if (MXRECT_VALID(trial))
				mx_vector_append(region, &trial, 1);

			MX__LEFT_RECTS(s, rrect, trial);
			if (MXRECT_VALID(trial))
				mx_vector_append(region, &trial, 1);

			MX__RIGHT_RECTS(s, rrect, trial);
			if (MXRECT_VALID(trial))
				mx_vector_append(region, &trial, 1);

			MX__BOT_RECTS(s, rrect, trial);
			if (MXRECT_VALID(trial))
				mx_vector_append(region, &trial, 1);
		}
	}
}
